import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { loginApi } from '@/apis/auth'
import { userByIdApi } from '@/apis/user'
import type { ILoginRequest } from '@/types/apis/auth'
import type { IUserResponse } from '@/types/apis/user'
import { dynamicRoutes } from '@/router/dynamicRoutes'
import { filterRoutesByRole } from '@/utils/permission'
import type { RouteRecordRaw } from 'vue-router'
import router from '@/router'

/**
 * 获取默认用户信息
 * @returns 默认用户信息
 */
function getDefaultUser(): IUserResponse {
  return {
    id: '',
    username: '',
    age: 0,
    email: '',
    phone: '',
    avatar: '',
    role: '',
    createTime: '',
    updateTime: '',
  }
}

export const useUserStore = defineStore(
  'User',
  () => {
    // token
    const token = ref('')
    // 用户信息
    const user = ref<IUserResponse>(getDefaultUser())
    // 判断是否登录
    const isLogin = computed(() => {
      return !!token.value
    })
    // 根据用户角色过滤路由
    const authorizedRoutes = ref<RouteRecordRaw[]>([])

    /**
     * 获取用户信息
     * @param userId 用户id
     */
    async function getUserInfo(userId: string | number) {
      try {
        user.value = await userByIdApi(userId)
      } catch (err) {
        showFailToast('获取用户信息失败')
        throw err
      }
    }

    /**
     * 登录
     * @param data 登录请求参数
     */
    async function login(data: ILoginRequest) {
      try {
        const { tokenType, accessToken, userId } = await loginApi(data)
        token.value = tokenType + ' ' + accessToken
        // 获取用户信息
        await getUserInfo(userId)
        // 根据用户角色过滤路由
        authorizedRoutes.value = filterRoutesByRole(dynamicRoutes, user.value.role)
        // 添加动态路由
        authorizedRoutes.value.forEach((route) => {
          router.addRoute(route)
        })
        return authorizedRoutes.value
      } catch (err) {
        showFailToast('登录失败')
        throw err
      }
    }

    /**
     * 退出登录
     */
    function logout() {
      token.value = ''
      user.value = getDefaultUser()
      authorizedRoutes.value = []
    }

    return {
      token,
      user,
      isLogin,
      authorizedRoutes,
      login,
      logout,
      getUserInfo,
    }
  },
  {
    persist: {
      key: 'User',
      storage: localStorage,
      pick: undefined, // undefined表示存储所有state，[]表示不存储任何state
    },
  },
)
